package com.cloud.controller.login;

import com.cloud.bean.user.User;
import com.cloud.common.BaseReturn;
import com.cloud.common.JwtUtils;
import com.cloud.controller.login.from.FromUser;
import com.cloud.controller.login.from.UserData;
import com.cloud.service.user.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author liuyuan
 * @Date 2022/7/19 9:59 AM
 * @Version 1.0
 */
@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping("/api/login")
    public BaseReturn login(@RequestBody FromUser fromUser){
        if(fromUser.getLoginType()== null){
            return BaseReturn.build("5000","登录平台不能为空");
        }
        if(fromUser.getMobile() == null){
            return BaseReturn.build("5000","请你输入手机号");
        }
        if(fromUser.getPassword()== null){
            return BaseReturn.build("5000","请你输入密码");
        }
        BaseReturn login = userService.login(fromUser);
        if(login.getCode().equals("2000")){
            User user = (User)login.getData();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            String token = JwtUtils.geneJsonWebToken(user.getId(), user.getMobile(), user.getUserRole());
            //key token value user.getId()
            session.setAttribute(token,user);
            UserData userData = new UserData();
            userData.setToken(token);
            BeanUtils.copyProperties(user,userData);
            return BaseReturn.build("2000",login.getMsg(),userData);
        }else {
           return BaseReturn.build("5000",login.getMsg());
        }
    }

    @RequestMapping("/api/logout")
    public BaseReturn logout(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        String token = request.getHeader("token");
        session.removeAttribute(token);
        return BaseReturn.build("2000","退出成功");
    }

    @RequestMapping("/api/register")
    public void register(){


    }
}
